#
#
#

class Factory:
    def __init__(self, cfg, out):
        self.cfg = cfg
        self.out = out
    def go(self,vn):
        self.fp = self.open()
        self.head_part()
        self.version(vn)
        self.constant()
        self.factory()
        self.tail_part()
        self.fp.close()
    def p(self, *m,end='\n'):
        print(*m, file=self.fp, end=end)
        #print(*m, end=end)
        
class JavaFactory(Factory):
    def __init__(self,cfg,out):
        super().__init__(cfg,out)
    def open(self):
        return open(self.out + 'VoFactory.java', 'w', 300, 'utf-8')
    def version(self,vn):
        self.p('public static final int VERSION = {0};'.format(vn))
    def head_part(self):
        self.p('''package com.showgood.vo;
import org.apache.log4j.Logger;
public class VoFactory {
private Logger logger = Logger.getLogger(getClass());''')
    def constant(self):
        for cls in self.cfg:
            self.p('public static final int VO_{0} = {1};'.format(cls['name'].upper(), cls['vid']))
    def tail_part(self):
        self.p('}')
    def factory(self):
        self.p('private static BaseVO[] prototype = new BaseVO[]{')
        for cls in self.cfg:
            name = cls['name']
            if name == 'BaseVO': continue
            self.p('new {0}(), // {1}'.format(name, cls['vid']))
        self.p('};')
        self.p('''public BaseVO create(int vid) {
try {
BaseVO vo = (BaseVO)prototype[vid-2].clone();
assert vo.getVid() == vid;
return vo;
} catch (CloneNotSupportedException e) {
logger.error("CREATE VO ERROR",e);
return null;
}}
private static VoFactory instance;
public static VoFactory getInstance() {if(instance==null){instance=new VoFactory();}return instance;}
''')

class As3Factory(Factory):
    def __init__(self,cfg,out):
        super().__init__(cfg,out)
    def open(self):
        return open(self.out + 'VoFactory.as', 'w', 300, 'utf-8')
    def version(self,vn):
        self.p('public static const VERSION:int = {0};'.format(vn))
    def head_part(self):
        self.p('''package com.showgood.vo {
public class VoFactory {''')
    def constant(self):
        for cls in self.cfg:
            self.p('public static const VO_{0}:int = {1};'.format(cls['name'].upper(), cls['vid']))
    def tail_part(self):
        self.p('}}')
    def factory(self):
        self.p('public function VoFactory() {')
        for cls in self.cfg:
            self.p('prototype.push({0}); // {1}'.format(cls['name'], cls['vid']))
        self.p('}')
        self.p('''private var prototype:Vector.<Class> = new Vector.<Class>();
private static var _instance:VoFactory;
public static function get instance():VoFactory {
if (_instance == null) {
_instance=new VoFactory();
}
return _instance;
}
public function create(vid:int):BaseVO{
return new prototype[vid-1]();
} 
''')
